package com.jewaton.auth.commons.action;

import com.jewaton.auth.commons.entity.Account;
import com.jewaton.auth.commons.operationlog.aspect.OperateLogAnnotation;
import com.jewaton.auth.commons.util.*;
import net.sf.json.JsonConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import static com.jewaton.auth.commons.operationlog.LogConstantAdmin.*;

/**
 * 账号管理ACTION
 */
public class AccountAction extends BaseAdminAction {

    private static final long serialVersionUID = 79341308426274996L;

    private static Log log = LogFactory.getLog(AccountAction.class);
    
	private static  Map<String,String> dutyMap = DutyUtil.getDutyMap();
    

	private Account acc;


	private String keywork1;
	
	public Account getAcc() {
		return acc;
	}
	public void setAcc(Account acc) {
		this.acc = acc;
	}


	
	@OperateLogAnnotation(moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ACCOUNT_MANAGER,operateTypeName=MG_ACCOUNT_MANAGER_QUERY,message=MG_ACCOUNT_MANAGER_QUERY_MSG)
	public String findAllPcAccount() {
	    setOrgSelectBoxInRequest();
	    String orgId = request.getParameter("orgId") == null ? getSessionOrgId() : request.getParameter("orgId");

        request.setAttribute("orgId", orgId);
        pager = getAccountService().getPcAccountPage(pager.getPageNo(), pager.getPageSize(),orgId, keywork1);
        return SUCCESS;

	}

	@Transactional
	@OperateLogAnnotation(
			moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ACCOUNT_MANAGER,
			operateTypeName=MG_ACCOUNT_MANAGER_ADDPCACCOUNT,
			message=MG_ACCOUNT_MANAGER_ADDPCACCOUNT_MSG,
			httpMethod="POST"
			)
	public String addPcAccount() {
	    
	    if(isGet()){
	    		request.setAttribute("dutyMap",dutyMap );
	            request.setAttribute("districtList", getAccountService().getFuzzyDistrictByDid(getSessionOrgId()));
	            return INPUT;
	    }
	    if(isPost()) {
	        if (!BeanUtil.checkProperties(Account.class, acc, new String[]{"username","password","realname"}))
	            return INPUT;
	        
    		acc.setUsername(StringUtil.trimToEmpty(acc.getUsername()));
    		acc.setPassword(CipherUtil.MD5Encode(StringUtil.trimToEmpty(acc.getPassword())));
    		acc.setRealname(StringUtil.trimToEmpty(acc.getRealname()));
    		acc.setMobile(StringUtil.trimToEmpty(acc.getMobile()));
    		acc.setCreateTime(new Date());
    		acc.setIsSystem(false);
    		acc.setCountLogin(0);
    		getAccountService().addAccount(acc);
    		request.getSession().setAttribute(Constants.SESSION_DO_FEEDBACK, "成功添加用户");
    		
    		return SUCCESS;
	    }
	    return INPUT;
	}
	
   @Transactional()
	@OperateLogAnnotation(
			moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ACCOUNT_MANAGER,
			operateTypeName=MG_ACCOUNT_MANAGER_DELETEPCACCOUNT,
			message=MG_ACCOUNT_MANAGER_DELETEPCACCOUNT_MSG,
			httpMethod="POST"
			)
	public String deletePcAccount() {
	    String aidArray = StringUtil.trimToEmpty(request.getParameter("aidArray"));
	    getAccountService().deleteManyAccount(aidArray);
	    request.getSession().setAttribute(Constants.SESSION_DO_FEEDBACK, "成功删除用户");
	    return SUCCESS;
	}

	
	
	/**
	 * 检测用户名是否可用  true:可用  false：重复不可用 
	 * @throws IOException 
	 */
	@Transactional()
	public void isValidName() {
	    String username = StringUtil.trimToEmpty(acc.getUsername());
	    Account checkName = getAccountService().getAccountByName(username);
	    if (checkName != null) {
//	        writeJSON("false");
	        WriteUtil.write(response, "false");
	    } else {
//	        writeJSON("true");
	        WriteUtil.write(response, "true");
	    }
	}
	
	/**
	 * 检测邮箱唯一性 true:可用  false：重复不可用 
	 */
	@Transactional()
	public void isValidEmail() {
	    String email = StringUtil.trimToEmpty(acc.getEmail());
	    Account checkEmail = getAccountService().getAccountByEmail(email);
	    if (checkEmail != null) {
	        WriteUtil.write(response, "false");
	    } else {
	        WriteUtil.write(response, "true");
	    }
	}
	
	/**
	 * 禁用启用账号 || 短信审核状态改变
	 */
	@Transactional
	@OperateLogAnnotation(
			moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ACCOUNT_MANAGER,
			operateTypeName=MG_ACCOUNT_MANAGER_CHANGESTATUS,
			message=MG_ACCOUNT_MANAGER_CHANGESTATUS_MSG
			)
	public void changeStatus() {
	    Account nAcc = getAccountService().getAccountById(acc.getAid());
	    if (acc.getDisabled() != null) {
	        nAcc.setDisabled(acc.getDisabled());
	    }

	    nAcc.setModifiedId(getSessionAid());
	    nAcc.setModifiedTime(new Date());
	    //update yourself need to refresh session 
	    if (nAcc.getAid().longValue() == getSessionAid()) {
	        request.getSession().setAttribute(Constants.SESSION_PC_ACCOUNT, nAcc);
	    }
	    
	    WriteUtil.write(response, "ok");
	}
	
	/**
	 * 自己修改密码
	 * @author czw
	 * @return
	 */
	@Transactional
	@OperateLogAnnotation(
			moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ACCOUNT_MANAGER,
			operateTypeName=MG_ACCOUNT_MANAGER_CHANGEPWD,
			message=MG_ACCOUNT_MANAGER_CHANGEPWD_MSG,
			httpMethod="POST"
			)
	public String changePwd() {
	    if (isGet()) {
	        return INPUT;
	    }
	    if (isPost()) {
	        Account nAcc = getAccountService().getAccountById(getSessionAid());
	        String newPwd = StringUtil.trimToEmpty(request.getParameter("new_pwd"));
	        if ("".equals(newPwd)) {
	            addActionError("新密码为空");
	            return INPUT;
	        }
	        if (!nAcc.getPassword().equals(CipherUtil.MD5Encode(acc.getPassword()))) {
	            addActionError("原密码错误");
	            return INPUT;
	        }
	        nAcc.setPassword(CipherUtil.MD5Encode(newPwd));
	        request.getSession().setAttribute(Constants.SESSION_DO_FEEDBACK, "修改密码成功，下次登录请使用新密码");
	        return SUCCESS;
	    }
	    return INPUT;
	}
	

    /**
     * 搜索用户，用于弹出层
     * input success返回页面由自己在业务Action指定	
     * @return
     */
	public String searchAccount() {
	    request.setAttribute("orgList", getAccountService().getFuzzyOrgByOid(getSessionOrgId(),""));
	    request.setAttribute("orgCode", StringUtil.trimToEmpty(request.getParameter("orgCode")));
	    if (isGet()) {
	        return INPUT;
	    }
	    if (isPost()) {
	        pager = getAccountService().searchAccount(acc.getOrganization().getOid(), acc.getUsername(), pager.getPageNo(), pager.getPageSize());
	        return SUCCESS;
	    }
	    return INPUT;
	}

	@Transactional
	public void getFuzzyOrgByOid() {
		String area = StringUtil.trimToEmpty(request.getParameter("area"));
	    JsonConfig config = new JsonConfig();
	    config.setExcludes(new String[]{"contacts","accounts","district"});
	    try {
	        this.writeJSONArray(getAccountService().getFuzzyOrgByOid(getSessionOrgId(),area), config);
	    } catch (IOException e) {
	        e.printStackTrace();
	        log.error(e);
	        throw new RuntimeException("getFuzzyOrgByOid fail : " + e);
	    }
	}
	@Transactional
	public void getOrgTreeByOid() {
	    try {
	        this.writeJSONArray(getAccountService().getOrgTreeByOid(getSessionOrgId()), new JsonConfig());
	    } catch (IOException e) {
	        e.printStackTrace();
	        log.error(e);
	        throw new RuntimeException("getOrgTreeByOid fail : " + e);
	    }
	}
	
	/**
	 * for jquery autocomplete
	 * @throws IOException 
	 */
	@Transactional
	public void getPcAccountByName() throws IOException {
	    String name = StringUtil.trimToEmpty(request.getParameter("term"));
	    if (log.isDebugEnabled()) {
	        log.debug("getPcAccountByName:===" + name);
	    }
	    writeJSONArray(getAccountService().getAccountListByName(name), new JsonConfig());
	}
	
	/**
	 * 编辑账户
	 * @return
	 */
	@Transactional
	@OperateLogAnnotation(
			moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ACCOUNT_MANAGER,
			operateTypeName=MG_ACCOUNT_MANAGER_EDITPCACCOUNT,
			message=MG_ACCOUNT_MANAGER_EDITPCACCOUNT_MSG,
			httpMethod="POST"
			)
	public String editPcAccount(){
		if (isGet()) {
			request.setAttribute("dutyMap",dutyMap );
			acc=getAccountService().getAccountById(acc.getAid());
			return INPUT;
		}
		if (isPost()) {
			String confirmPassword = StringUtil.trim(request.getParameter("confirm_password"));
			Account account=getAccountService().getAccountById(acc.getAid());
			acc.setModifiedTime(new Date());
			if(!StringUtil.isEmpty(acc.getPassword())) {
				if(acc.getPassword().equals(confirmPassword)) {
					acc.setPassword(CipherUtil.MD5Encode(acc.getPassword()));
					BeanUtil.copyNotNullProperties(acc, account, new String[]{"aid","username","email","mobile"});
				}else {
					addActionError("两次输入的密码不一致！");
					return INPUT;
				}
			}else {
				BeanUtil.copyNotNullProperties(acc, account, new String[]{"aid","username","email","mobile","password"});
			}
			return SUCCESS;
		}
		return INPUT;
	}
	
	/**
	 * 个人资料修改
	 * @return
	 */
	@Transactional
	@OperateLogAnnotation(
			moduleName=SYSTEM_MANAGER+UNDERLINE+MG_ACCOUNT_MANAGER,
			operateTypeName=MG_ACCOUNT_MANAGER_UPDATEPCACCOUNT,
			message=MG_ACCOUNT_MANAGER_UPDATEPCACCOUNT_MSG,
			httpMethod="POST"
			)
	public String updatePcAccount() {
		if (isGet()) {
			acc = getAccountService().getAccountById(getSessionAid());
		}
		if(isPost()){
			Account newAcc = getAccountService().getAccountById(getSessionAid());
			newAcc.setRealname(acc.getRealname());
			newAcc.setMobile(acc.getMobile());
			newAcc.setEmail(acc.getEmail());

			request.getSession().setAttribute(Constants.SESSION_DO_FEEDBACK, "成功修改信息");
			
		}
		return SUCCESS;
	}
	
	public String getKeywork1() {
		return keywork1;
	}
	public void setKeywork1(String keywork1) {
		this.keywork1 = keywork1;
	}	
}
